package com.huixi.microspur.sysadmin.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.huixi.microspur.commons.page.PageData;
import com.huixi.microspur.commons.page.PageFactory;
import com.huixi.microspur.sysadmin.mapper.WjDynamicMapper;
import com.huixi.microspur.sysadmin.pojo.dto.dynamic.WjDynamicPageDTO;
import com.huixi.microspur.sysadmin.pojo.entity.dynamic.WjDynamic;
import com.huixi.microspur.sysadmin.pojo.entity.dynamic.WjDynamicComment;
import com.huixi.microspur.sysadmin.pojo.entity.dynamic.WjDynamicEndorse;
import com.huixi.microspur.sysadmin.pojo.entity.user.WjUser;
import com.huixi.microspur.sysadmin.pojo.vo.dynamic.DynamicInfoVO;
import com.huixi.microspur.sysadmin.pojo.vo.dynamic.QueryDynamicVO;
import com.huixi.microspur.sysadmin.service.WjDynamicCommentService;
import com.huixi.microspur.sysadmin.service.WjDynamicEndorseService;
import com.huixi.microspur.sysadmin.service.WjDynamicService;
import com.huixi.microspur.sysadmin.service.WjUserService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * <p>
 * 动态表 服务实现类
 * </p>
 *
 * @author xzl
 * @since 2020-01-17
 */
@Service
public class WjDynamicServiceImpl extends ServiceImpl<WjDynamicMapper, WjDynamic> implements WjDynamicService {

    @Resource
    private WjUserService wjUserService;

    @Resource
    private WjDynamicEndorseService wjDynamicEndorseService;

    @Resource
    private WjDynamicCommentService wjDynamicCommentService;


    public PageData<QueryDynamicVO> listPageDynamic(WjDynamicPageDTO wjDynamicPageVO, Boolean isMe) {

        PageData<QueryDynamicVO> pageData = new PageData<>();

        List<QueryDynamicVO> queryDynamicVOList = new ArrayList<>();


        // 查询条件
        QueryWrapper<WjDynamic> objectQueryWrapper = new QueryWrapper<>();

        // 是否是 查询自己的
        if(isMe){
            objectQueryWrapper.eq("user_id",wjDynamicPageVO.getUserId());
        }
        if(StrUtil.isNotBlank(wjDynamicPageVO.getContent())){
            objectQueryWrapper.like("content", wjDynamicPageVO.getContent());
        }
        if(wjDynamicPageVO.getCreateTime()){
            objectQueryWrapper.orderByDesc("create_time");
        }
        if(wjDynamicPageVO.getEndorseCount()){
            objectQueryWrapper.orderByDesc("endorse_count");
        }


        // 分页条件
        Page<WjDynamic> page = PageFactory.createPage(wjDynamicPageVO.getPageQuery());
        Page<WjDynamic> wjDynamicPage = page(page, objectQueryWrapper);

        // 查询列表中自己点过赞的
        Set<String> dynamicIdSet =
                wjDynamicPage.getRecords().stream().map(WjDynamic::getDynamicId).collect(Collectors.toSet());
        List<WjDynamicEndorse> wjDynamicEndorseList = wjDynamicEndorseService.lambdaQuery()
                .in(WjDynamicEndorse::getDynamicId, dynamicIdSet)
                .eq(WjDynamicEndorse::getUserId, wjDynamicPageVO.getUserId()).list();

        // 各个动态 点赞数
        List<WjDynamicEndorse> dynamicEndorses = wjDynamicEndorseService.lambdaQuery()
                .in(CollUtil.isNotEmpty(dynamicIdSet), WjDynamicEndorse::getDynamicId, dynamicIdSet).list();
        Map<String, Long> dynamicEndorseMap = dynamicEndorses.stream()
                .collect(Collectors.groupingBy(WjDynamicEndorse::getDynamicId, Collectors.counting()));

        // 各个动态 评论数
        List<WjDynamicComment> dynamicComments = wjDynamicCommentService.lambdaQuery()
                .in(CollUtil.isNotEmpty(dynamicIdSet), WjDynamicComment::getDynamicId, dynamicIdSet).list();
        Map<String, Long> dynamicCommentMap = dynamicComments.stream()
                .collect(Collectors.groupingBy(WjDynamicComment::getDynamicId, Collectors.counting()));


        // 发帖用户集合
        Set<String> userIds = wjDynamicPage.getRecords().stream().map(WjDynamic::getUserId).collect(Collectors.toSet());
        List<WjUser> wjUserList = wjUserService.lambdaQuery().in(WjUser::getUserId, userIds).list();


        QueryDynamicVO queryDynamicVO;
        // 循环判断查询
        for (WjDynamic record : wjDynamicPage.getRecords()) {

            queryDynamicVO = new QueryDynamicVO();

            BeanUtil.copyProperties(record, queryDynamicVO);

            // 判断是否点赞
            queryDynamicVO.setIsEndorse(false);
            if(StrUtil.isNotEmpty(wjDynamicPageVO.getUserId())) {
                Boolean endorse = wjDynamicEndorseList.stream().anyMatch(e -> StrUtil.equals(e.getDynamicId(), record.getDynamicId()));
                queryDynamicVO.setIsEndorse(endorse);
            }

            // 点赞数量
            int totalCount = dynamicEndorseMap.get(record.getDynamicId()) == null ? 0 : dynamicEndorseMap.get(record.getDynamicId()).intValue();
            queryDynamicVO.setEndorseCount(totalCount);

            // 评论总数
            int commentCount = dynamicCommentMap.get(record.getDynamicId()) == null ? 0 : dynamicCommentMap.get(record.getDynamicId()).intValue();
            queryDynamicVO.setCommentCount(commentCount);

            // 评论前三的用户头像
            List<WjDynamicComment> dynamicCommentList = wjDynamicCommentService.lambdaQuery()
                    .eq(WjDynamicComment::getDynamicId, record.getDynamicId())
                    .orderByDesc(WjDynamicComment::getCreateTime)
                    .page(new Page<>(1, 3)).getRecords();
            Set<String> commentUserIds =
                    dynamicCommentList.stream().map(WjDynamicComment::getUserId).collect(Collectors.toSet());
            if(commentUserIds.size()!=0){
                List<String> collect = wjUserService.lambdaQuery()
                        .in(WjUser::getUserId, commentUserIds).list().stream().map(WjUser::getHeadPortrait).collect(Collectors.toList());
                queryDynamicVO.setCommentUserHeadPortrait(collect);
            }



            // 发帖用户信息
            WjUser wjUser = wjUserList.stream().filter(e -> e.getUserId().equals(record.getUserId())).findAny().orElseGet(WjUser::new);
            queryDynamicVO.setNickName(wjUser.getNickName()).setHeadPortrait(wjUser.getHeadPortrait());


            queryDynamicVOList.add(queryDynamicVO);

        }

        BeanUtil.copyProperties(wjDynamicPage, pageData);
        pageData.setRecords(queryDynamicVOList);

        return pageData;
    }


    @Override
    public Boolean judgeIsMeDynamic(String userId, String dynamicId) {

        LambdaQueryWrapper<WjDynamic> eq = Wrappers.<WjDynamic>lambdaQuery()
                .eq(WjDynamic::getUserId, userId)
                .eq(WjDynamic::getDynamicId, dynamicId);

        WjDynamic one = getOne(eq);
        return ObjectUtil.isNotNull(one);
    }

    @Override
    public PageData<QueryDynamicVO> listPageDynamic(WjDynamicPageDTO wjDynamicPageVO) {
        return listPageDynamic(wjDynamicPageVO, false);
    }

    @Override
    public PageData<QueryDynamicVO> listPageMyDynamic(WjDynamicPageDTO wjDynamicPageVO) {
        return listPageDynamic(wjDynamicPageVO, true);
    }

    @Override
    public DynamicInfoVO get(String id) {
        WjDynamic dynamic = getById(id);
        return DynamicInfoVO.convert(dynamic);
    }


}
